const fs = require('fs')
const path = require('path')

// 获取项目根目录
const projectRoot = path.resolve(__dirname, '../')
const gitHooksDir = path.join(projectRoot, '.git', 'hooks')

// 确保 .git/hooks 目录存在
if (!fs.existsSync(gitHooksDir)) {
  console.error('Error: .git/hooks directory not found. Please run this script in a git repository.')
  process.exit(1)
}

// 创建 pre-commit 钩子内容
const preCommitContent = `#!/bin/bash
# 自动更新 commit 时间戳并处理 lint
echo "Running pre-commit hook..."
node scripts/updateCommitTime.js
`

// 写入 pre-commit 钩子文件
const preCommitPath = path.join(gitHooksDir, 'pre-commit')
fs.writeFileSync(preCommitPath, preCommitContent)

// 设置执行权限 (在 Windows 上可能不需要，但在 Linux/Mac 上需要)
try {
  fs.chmodSync(preCommitPath, '755')
  console.log('Successfully installed pre-commit hook with executable permissions')
} catch (err) {
  console.log('Installed pre-commit hook (chmod may not be supported on this system)')
}

console.log('Git pre-commit hook installed successfully!')
console.log('The hook will automatically update the commit timestamp in config/index.js before each commit.')
